<template>
  <div class="app-container">
    <div class="filter-container">
      <el-col :md="15">
        <el-input v-model="listQuery.sid[0]" placeholder="开始服务器ID" style="width: 120px;"></el-input>
        <el-input v-model="listQuery.sid[1]" placeholder="结束服务器ID" style="width: 120px;"></el-input>
        <el-select v-model="listQuery.server_region" filterable clearable class="filter-item" style="width: 120px;" placeholder="大区">
          <el-option
            v-for="(item, index) in serverRegionList"
            :key="index"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
        <el-select v-model="listQuery.status" clearable class="filter-item" style="width: 120px;" placeholder="服务器状态">
          <el-option
            v-for="(item, index) in statusList"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select v-model="listQuery.is_recommend	" clearable class="filter-item" style="width: 120px;" placeholder="推荐状态">
          <el-option label="否" value="0" />
          <el-option label="是" value="1" />
        </el-select>

        <el-input v-model="listQuery.ip" placeholder="IP" style="width: 120px;"></el-input>
        <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
        <el-button v-if="checkPermission(permissionRoles.server_single_add)" v-waves type="success" class="filter-item" @click="handleAdd">单个添加</el-button>
      </el-col>
      <el-col :md="9">
        <el-select v-if="checkPermission(permissionRoles.server_batch_modify_status)" v-model="status" clearable class="filter-item" style="width: 110px;" placeholder="服务器状态" @change="changeStatus">
          <el-option
            v-for="(item, index) in statusList"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select v-if="checkPermission(permissionRoles.server_batch_modify_recommend)" v-model="is_recommend" clearable class="filter-item" style="width: 110px;" placeholder="推荐状态" @change="changeRecommend">
          <el-option label="否" value="0" />
          <el-option label="是" value="1" />
        </el-select>
        <el-button v-if="checkPermission(permissionRoles.server_batch_modify_group)" v-waves type="warning" class="filter-item" @click="dialogGroup=true">修改分组</el-button>
        <el-button v-if="checkPermission(permissionRoles.server_batch_add)" v-waves type="primary" class="filter-item" @click="dialogBatchAdd=true">批量添加</el-button>
        <el-button v-if="checkPermission(permissionRoles.server_kick_out)" v-waves type="danger" class="filter-item" @click="kickOut()">踢下线</el-button>
      </el-col>
    </div>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      :default-sort="{prop: 'sid', order: 'descending'}"
      highlight-current-row
      style="width: 100%; margin-top: 20px;"
      height="705"
      @sort-change="sortChange"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50"></el-table-column>
      <el-table-column label="服务器ID" sortable prop="sid" width="100" align="center"></el-table-column>
      <el-table-column label="服务器名" prop="name" align="center"></el-table-column>
      <el-table-column label="合服ID" prop="merge_id" width="100" align="center"></el-table-column>
      <el-table-column label="大区" prop="srname" align="center"></el-table-column>
      <el-table-column label="分组" prop="sgname" width="150px" align="center"></el-table-column>
      <el-table-column label="服务器IP" prop="ip" min-width="105px" align="center"></el-table-column>
      <el-table-column label="状态" class-name="status-col" width="80" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.status | statusTagFilter">{{ row.status | statusFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="推荐" class-name="status-col" width="80" align="center">
        <template slot-scope="{row}">
          <el-tag v-if="row.is_recommend === '0'" type="danger">否</el-tag>
          <el-tag v-else type="success">是</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="显示" prop="is_display" width="80px" align="center">
        <template slot-scope="{row}">
          <el-tag v-if="row.is_display === 0" type="info">否</el-tag>
          <el-tag v-else type="success">是</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="开服时间" prop="open_time" width="180px" align="center"></el-table-column>
      <el-table-column label="开服状态" class-name="status-col" width="90" align="center">
        <template slot-scope="{row}">
          <el-tag v-if="row.open_status === 0" type="danger">未开服</el-tag>
          <el-tag v-else type="success">已开服</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="标记" class-name="status-col" width="90" align="center">
        <template slot-scope="{row}">
          <el-tag v-if="row.tag === '1'" type="success">新服</el-tag>
          <el-tag v-else-if="row.tag === '2'" type="warning">推荐</el-tag>
          <el-tag v-else type="info">无</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="关联ID" prop="sr_correlation_id" width="100" align="center"></el-table-column>
      <el-table-column align="center" label="操作" fixed="right">
        <template slot-scope="scope">
          <el-button v-if="checkPermission(permissionRoles.server_single_edit)" type="text" size="small" title="编辑" @click="handleEdit(scope)">修改</el-button>
          <el-button v-if="checkPermission(permissionRoles.server_single_del)" type="text" size="small" title="删除" @click="handleDelete(scope)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :visible.sync="dialogVisible" :title="textMap[dialogType]" :close-on-click-modal="false" width="80%" class="server-container">
      <el-form ref="dataForm" :model="dataForm" :rules="rules" label-width="120px">
        <el-row>
          <el-col :md="12">
            <el-form-item label="区服ID" prop="sid">
              <el-input v-model="dataForm.sid" :disabled="sidDisabled" />
            </el-form-item>
          </el-col>
          <el-col :md="12">
            <el-form-item label="区服名" prop="name">
              <el-input v-model="dataForm.name" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :md="12">
            <el-form-item label="大区" prop="srid">
              <el-select v-model="dataForm.srid" clearable class="filter-item" style="width: 120px;" placeholder="大区">
                <el-option
                  v-for="(item, index) in serverRegionList"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="12">
            <el-form-item label="分组" prop="sgid">
              <el-select v-model="dataForm.sgid" class="filter-item" placeholder="分组">
                <el-option
                  v-for="(item, index) in serverGroupList"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :md="12">
            <el-form-item label="IP" prop="ip">
              <el-input v-model="dataForm.ip" />
            </el-form-item>
          </el-col>
          <el-col :md="12">
            <el-form-item label="端口" prop="port">
              <el-input v-model="dataForm.port" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :md="12">
            <el-form-item label="前端IP" prop="frontip">
              <el-input v-model="dataForm.frontip" />
            </el-form-item>
          </el-col>
          <el-col :md="12">
            <el-form-item label="前端端口" prop="frontport">
              <el-input v-model="dataForm.frontport" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :md="4">
            <el-form-item label="数据库IP" prop="dbhost">
              <el-input v-model="dataForm.dbhost" :placeholder="serverConfig.host" />
            </el-form-item>
          </el-col>
          <el-col :md="4">
            <el-form-item label="数据库端口" prop="dbport">
              <el-input v-model="dataForm.dbport" :placeholder="serverConfig.port" />
            </el-form-item>
          </el-col>
          <el-col :md="4">
            <el-form-item label="数据库名" prop="dbname">
              <el-input v-model="dataForm.dbname" :placeholder="serverConfig.name" />
            </el-form-item>
          </el-col>
          <el-col :md="4">
            <el-form-item label="数据库账号" prop="dbusername">
              <el-input v-model="dataForm.dbusername" :placeholder="serverConfig.username" />
            </el-form-item>
          </el-col>
          <el-col :md="4">
            <el-form-item label="数据库密码" prop="dbpassword">
              <el-input v-model="dataForm.dbpassword" type="text" autocomplete="off" :placeholder="serverConfig.password" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :md="4">
            <el-form-item label="日志数据库IP" prop="dbloghost">
              <el-input v-model="dataForm.dbloghost" :placeholder="logConfig.host" />
            </el-form-item>
          </el-col>
          <el-col :md="4">
            <el-form-item label="日志数据库端口" prop="dblogport">
              <el-input v-model="dataForm.dblogport" :placeholder="logConfig.port" />
            </el-form-item>
          </el-col>
          <el-col :md="4">
            <el-form-item label="日志数据库名" prop="dblogname">
              <el-input v-model="dataForm.dblogname" :placeholder="logConfig.name" />
            </el-form-item>
          </el-col>
          <el-col :md="4">
            <el-form-item label="数据库账号" prop="dblogusername">
              <el-input v-model="dataForm.dblogusername" :placeholder="logConfig.username" />
            </el-form-item>
          </el-col>
          <el-col :md="4">
            <el-form-item label="日志数据库密码" prop="dblogpassword" autocomplete="off">
              <el-input v-model="dataForm.dblogpassword" type="text" :placeholder="logConfig.password" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :md="12">
            <el-form-item label="服务器状态" prop="status">
              <el-select v-model="dataForm.status" clearable class="filter-item" style="width: 120px;" placeholder="服务器状态">
                <el-option
                  v-for="(item, index) in statusList"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="12">
            <el-form-item label="推荐状态" prop="is_recommend">
              <el-select v-model="dataForm.is_recommend" clearable class="filter-item" style="width: 120px;" placeholder="推荐状态">
                <el-option label="否" value="0" />
                <el-option label="是" value="1" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :md="12">
            <el-form-item label="服务器标记" prop="tag">
              <el-select v-model="dataForm.tag" clearable class="filter-item" style="width: 120px;" placeholder="服务器标记">
                <el-option label="无" value="0" />
                <el-option label="新服" value="1" />
                <el-option label="推荐" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="12">
            <el-form-item label="合服ID" prop="merge_id">
              <el-input v-model="dataForm.merge_id" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :md="12">
            <el-form-item label="显示" prop="is_display">
              <el-radio-group v-model="dataForm.is_display">
                <el-radio :label="0">否</el-radio>
                <el-radio :label="1">是</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :md="12">
            <el-form-item label="开服时间" prop="open_time">
              <el-date-picker
                v-model="dataForm.open_time"
                type="datetime"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :md="12">
            <el-form-item label="关联ID">
              <el-input v-model="dataForm.sr_correlation_id" :disabled="srcidDisabled" />
            </el-form-item>
          </el-col>
          <el-col :md="12">
            <el-form-item label="创角限制">
              <el-input v-model="dataForm.open_days" style="width: 100px;" placeholder="开服天数" /><el-input v-model="dataForm.create_roles" style="width: 100px;" placeholder="创角数量" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="tr">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmSubmit()">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogGroup" title="修改分组" :close-on-click-modal="false">
      <el-form ref="groupForm" :model="groupForm" :rules="rules" label-width="120px">
        <el-row>
          <el-col :md="24">
            <el-form-item label="分组" prop="sgids">
              <el-select v-model="groupForm.sgids" size="medium" style="width: 300px;" class="filter-item" placeholder="选择分组">
                <el-option
                  v-for="(item, index) in serverGroupList"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="tr">
        <el-button type="danger" @click="dialogGroup = false">取消</el-button>
        <el-button type="primary" @click="groupConfirmSubmit()">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogBatchAdd" title="批量添加服务器" :close-on-click-modal="false">
      <el-form ref="batchAddServerForm" :model="batchAddServerForm" :rules="rules" label-width="120px">
        <el-row>
          <el-col :md="24">
            <el-form-item label="服务器区间" prop="sids">
              <el-input v-model="batchAddServerForm.sids[0]" placeholder="开始服务器ID" style="width: 120px;"></el-input> -
              <el-input v-model="batchAddServerForm.sids[1]" placeholder="结束服务器ID" style="width: 120px;"></el-input>
            </el-form-item>
          </el-col>
          <el-col :md="16">
            <el-form-item label="区服名" prop="name">
              <el-input v-model="batchAddServerForm.name" />
            </el-form-item>
          </el-col>

          <el-col :md="24">
            <el-form-item label="大区" prop="srids">
              <el-select v-model="batchAddServerForm.srid" size="medium" style="width: 300px;" class="filter-item" placeholder="选择大区">
                <el-option
                  v-for="(item, index) in serverRegionList"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="24">
            <el-form-item label="分组" prop="sgids">
              <el-select v-model="batchAddServerForm.sgids" size="medium" style="width: 300px;" class="filter-item" placeholder="选择分组">
                <el-option
                  v-for="(item, index) in serverGroupList"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="tr">
        <el-button type="danger" @click="dialogBatchAdd = false">取消</el-button>
        <el-button type="primary" @click="batchAddConfirmSubmit()">确定</el-button>
      </div>
    </el-dialog>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
  </div>
</template>

<script>

import checkPermission from '@/utils/permission' // 权限判断函数
import { objectMerge, deepClone } from '@/utils'
import waves from '@/directive/waves' // 实现点击波浪纹
import Pagination from '@/components/Pagination'
import { getServerRegionList, getServerGroupList, getServerList, handleServer, batchModifyServerGroup, batchAddServer, batchModifyRecommend, batchModifyStatus, deleteServer, kickPlayerOut } from '@/api/ops'

export default {
  name: 'Server',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        0: '无状态',
        1: '流畅',
        2: '拥挤',
        3: '火爆',
        4: '维护'
      }
      return statusMap[status]
    },
    statusTagFilter(status) {
      const statusTagMap = {
        0: 'primary',
        1: 'success',
        2: 'warning',
        3: 'danger',
        4: 'info'
      }
      return statusTagMap[status]
    }
  },
  data() {
    return {
      permissionRoles: this.$store.state.user.permissionRoles,
      tableKey: 0,
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 200,
        type: '',
        sid: [],
        ip: '',
        sort: '-id'
      },
      logConfig: {},
      serverConfig: {},
      multipleSelection: [],
      searchBarQuery: {},
      statusOptions: ['0', '1', '2', '3', '4'],
      dialogVisible: false,
      dialogGroup: false,
      dialogBatchAdd: false,
      sidDisabled: false,
      srcidDisabled: false,
      dialogType: 'new',
      textMap: {
        edit: '编辑服务器',
        new: '添加服务器'
      },
      dataForm: {
        id: '',
        sgid: '',
        srid: '',
        sid: '',
        name: '',
        merge_id: 0,
        ip: '',
        port: '',
        frontip: '',
        frontport: '',
        dbhost: '',
        dbport: '',
        dbname: '',
        dblogname: '',
        open_time: new Date(2034, 1, 1),
        is_display: 0,
        status: 1,
        tag: '0',
        open_days: '',
        create_roles: '',
        is_recommend: '1',
        is_white: 0,
        sr_correlation_id: ''
      },
      rules: {
        sid: [{ required: true, message: '填写区服ID', trigger: 'blur' }],
        srid: [{ required: true, message: '选择大区', trigger: 'blur' }],
        sgid: [{ required: true, message: '选择分组', trigger: 'blur' }],
        name: [{ required: true, message: '填写区服名', trigger: 'blur' }]
      },
      serverRegionList: [],
      serverGroupList: [],
      showGame: false,
      is_recommend: '',
      status: '',
      groupForm: {
        sgids: ''
      },
      batchAddServerForm: {
        srid: '',
        sids: [],
        name: '',
        sgids: ''
      },
      statusList: [
        { value: 0, label: '无状态' },
        { value: 1, label: '流畅' },
        { value: 2, label: '拥挤' },
        { value: 3, label: '火爆' },
        { value: 4, label: '维护	' }
      ]
    }
  },

  created() {
    this.getList()
    this.getServerRegionList()
    this.getServerGroupList()
  },
  methods: {
    checkPermission,
    // 重置数据
    resetServerForm() {
      this.dataForm = {
        id: '',
        sgid: '',
        srid: '',
        sid: '',
        name: '',
        merge_id: 0,
        ip: '',
        port: '',
        frontip: '',
        frontport: '',
        dbhost: '',
        dbport: '',
        dbname: '',
        dblogname: '',
        open_time: new Date(2034, 1, 1),
        status: 1,
        is_display: 0,
        tag: '0',
        open_days: '',
        create_roles: '',
        is_recommend: '1',
        is_white: 0,
        sr_correlation_id: ''
      }
    },
    getList() {
      this.listLoading = true
      let params = objectMerge(this.searchBarQuery, this.listQuery)
      params = Object.assign(params, { data_type: 'page' })
      getServerList(params).then(response => {
        this.list = response.data.items
        this.total = response.data.total
        this.logConfig = response.data.logConfig
        this.serverConfig = response.data.serverConfig
        this.listLoading = false
      })
    },
    async getServerRegionList() {
      const res = await getServerRegionList()
      this.serverRegionList = res.data
    },
    async getServerGroupList() {
      const res = await getServerGroupList()
      this.serverGroupList = res.data
    },
    handleFilter() {
      this.searchBarQuery = this.listQuery
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    handleAdd() {
      this.resetServerForm()
      this.showGame = false
      this.sidDisabled = false
      this.srcidDisabled = true
      this.dialogType = 'new'
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleEdit(scope) {
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.sidDisabled = true
      this.srcidDisabled = false
      this.dataForm = deepClone(scope.row)
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      this.showGame = true
    },
    handleDelete({ $index, row }) {
      this.$confirm('你确定要删除此列吗?', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          if (row.open_status === 1) {
            this.$message({ type: 'error', message: '当前服已开服，不能执行删除操作' })
            return
          }
          await deleteServer(row.id)
          this.getList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(err => { console.error(err) })
    },
    async changeRecommend(val) {
      this.$confirm('你确定要修改推荐状态吗?', '修改', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const data = {
            recommend: val,
            selection: this.multipleSelection
          }
          batchModifyRecommend(data).then(response => {
            if (response.status) {
              this.getList()
              this.$message.success('操作成功!')
            } else {
              this.message.error(response.message)
            }
          })
        })
    },
    async changeStatus(val) {
      this.$confirm('你确定要修改服务器状态吗?', '修改', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const data = {
            status: val,
            selection: this.multipleSelection
          }
          batchModifyStatus(data).then(response => {
            if (response.status) {
              this.getList()
              this.$message.success('操作成功!')
            } else {
              this.message.error(response.message)
            }
          })
        })
    },
    async kickOut(val) {
      this.$confirm('你确定要踢玩家下线吗?', '踢下线', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const data = {
            selection: this.multipleSelection
          }
          kickPlayerOut(data).then(response => {
            if (response.status) {
              this.getList()
              this.$message.success('操作成功!')
            } else {
              this.message.error(response.message)
            }
          })
        })
    },
    confirmSubmit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const isEdit = this.dialogType === 'edit'
          handleServer(this.dataForm).then(response => {
            if (response.status) {
              if (isEdit) {
                for (let index = 0; index < this.list.length; index++) {
                  if (this.list[index].id === this.dataForm.id) {
                    this.list.splice(index, 1, Object.assign({}, response.data))
                    console.log(this.list[index])
                    break
                  }
                }
              } else {
                this.list.push(response.data)
              }
              this.dialogVisible = false
              this.getList()
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
            } else {
              this.message.error(response.message)
            }
          })
        }
      })
    },
    groupConfirmSubmit() {
      this.$confirm('你确定要修改分组吗?', '修改', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const data = {
            sgids: this.groupForm.sgids,
            selection: this.multipleSelection
          }
          batchModifyServerGroup(data).then(response => {
            if (response.status) {
              this.dialogGroup = false
              this.getList()
              this.$message.success('操作成功!')
            } else {
              this.message.error(response.message)
            }
          })
        })
    },
    batchAddConfirmSubmit() {
      batchAddServer(this.batchAddServerForm).then(response => {
        console.log(response)
        if (response.status) {
          this.dialogBatchAdd = false
          this.getList()
          this.$message.success('操作成功!')
        } else {
          this.message.error('操作失败或部分区服已存在')
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.filter-container {
  height: 30px;
}

.filter-container .filter-item {
  margin-bottom: 0px;
}

.el-input {
  margin-right: 5px;
}

.el-table {
  font-size: 14px;
}

.el-table td, .el-table th {
  padding: 10px 0;
}

.el-table th>.cell {
  padding-left: 10px;
  padding-right: 10px;
}
.server-container .el-row{
  display: flex;
  justify-content: space-between;
}
</style>
